<template>
    <view class="page" :style="{ 'min-height': reqsItem.id ? '90vh' : '100vh' }">

        <view class="ing" v-if="!reqsItem.taskId">
            <!--        <view class="ing" v-if="!reqsItem.taskId"> -->
            <view class="title">
                <text class="tel">正在生成中，请耐心等待...</text>
                <text class="status">{{ reqsItem.progress ?? 0 }}%</text>
            </view>
            <view class="progress-container">
                <view class="content">
                    <uv-line-progress :percentage="reqsItem.progress ?? 0" height="4"
                        :showText="false"></uv-line-progress>
                </view>
            </view>
            <view class="tip-container">
                <view class="tip">提示：中途离开本页面不影响创作</view>
                <view class="tip">绘图完成请前往【我的】-我的作品查看结果</view>
            </view>
        </view>

        <view class="content" v-if="reqsItem.taskId">
            <swiper class="swiper" circular autoplay interval="5000" current="0" @change="intervalChange">
                <swiper-item class="swiper-item" v-for="(item, i) in reqsItem.resultImages" :key="i">
                    <view class="swiper-item">
                        <uv-image v-if="item" class="swiper-item-img" :src="item" mode="aspectFit" width="100%"
                            height="100%" @click="previewImage"></uv-image>
                        <view class="block" v-else>
                            <uv-icon class="block-icon" name="info-circle-fill" color="#999" size="40"></uv-icon>
                            <text class="text">本次生成图片可能有些偏差！</text>
                            <text class="text">请尝试重新生成</text>
                        </view>
                    </view>
                </swiper-item>
            </swiper>
            <view class="dots">
                <view class="dots-item" :class="{ actived: index == i }" v-for="(item, i) in reqsItem.resultImages"
                    :key="i"></view>
            </view>
        </view>

        <view class="btn-conainer " v-if="reqsItem.taskId">
            <view v-if="!reqsItem.resultImages[index]" class="high disabled">转高清修复大图</view>
            <navigator v-else
                :url="'/pages/highDefinition/highDefinition?id=' + reqsItem.taskId + '&img=' + reqsItem.resultImages[index] + '&index=' + index"
                hover-class="none" open-type="navigate" class="high">转高清修复大图</navigator>

            <view v-if="!reqsItem.downLoadList[index]" class="down disabled">下载</view>
            <view v-else class="down" @click="download">下载</view>
        </view>

        <view class="controller" v-if="reqsItem.taskId">
            <view class="batch">
                <view class="text">每次生成张数</view>
                <view class="batch-container">
                    <view class="item" :class="{ actived: batch_index == i }" v-for="(item, i) in picBatch" :key="i"
                        @click="batch_index = i">
                        {{ item.name }}
                    </view>
                </view>
            </view>
            <view class="work-btn-style btn" @click="getImg2Img">
                <text class="btn-text">点击生成</text>
                <text class="btn-price">（本次消耗{{ (cost * (picBatch[batch_index].value * 100)) / 100 }}点积分）</text>
            </view>
        </view>

        <!-- loading -->
        <uv-loading-page :loading="loading" :loadingText="loadingText" font-size="24rpx"
            bgColor="rgba(0,0,0,0.5)"></uv-loading-page>

        <fab :type="fabType" />

    </view>
</template>

<script setup>
import {
    onLoad,
    onHide
} from '@dcloudio/uni-app'
import {
    ref
} from 'vue';
import {
    downloadImg,
    previewModel
} from "@/utils/utils.js";


import {
    apiGetReqsStatus,
    BASE_URL
} from '@/api/defaultApi.js'

//pinia
import {
    storeToRefs
} from 'pinia'
import {
    useUserStore
} from "@/stores/useUserStore.js"
import {
    useLoadingStore
} from "@/stores/useLoadingStore.js"

// 获取pinia的数据
const userStore = useUserStore()
const loadingStore = useLoadingStore()

// 从pinia的数据中结构出值并做响应式
const {
    token
} = storeToRefs(userStore)
const {
    loading
} = storeToRefs(loadingStore)



const id = ref('')
const filedata = ref('')
const filedata1 = ref('')
const filedata2 = ref('')
const formdata = ref({})

//任务结果对象
const index = ref(0)
const reqsItem = ref({})

//生成数量相关
const picBatch = ref([{
    name: 1,
    value: 1
},
{
    name: 2,
    value: 2
},
{
    name: 3,
    value: 3
},
{
    name: 4,
    value: 4
}
])
const batch_index = ref(0)
//消耗积分数量
const cost = ref(0)

//定时器
const count = ref(100000)

const loadingText = ref('图片上传中...')

const fabType = ref('index')

onLoad((option) => {
    id.value = option.id
    let jsnoForm = JSON.parse(option.formData)
    filedata.value = jsnoForm.filedata
    filedata1.value = jsnoForm.filedata1
    filedata2.value = jsnoForm.filedata2
    formdata.value = JSON.parse(jsnoForm.paramStr)
    cost.value = jsnoForm.cost

    const timer = setInterval(() => {
        getReqsStatus()
        count.value = count.value - 1

        if (reqsItem.value.taskId || count.value == 0) {
            clearInterval(timer)
        }

    }, 3000)
})

// 获取生成图片任务状态
const getReqsStatus = async () => {
    let res = await apiGetReqsStatus({
        id: id.value,
        type: 'img2img'
    })
    reqsItem.value = res.data
    if (res.data?.resultStatistics?.block_num > 0) {
        for (let index = 0; index < res.data?.resultStatistics?.block_num; index++) {
            reqsItem.value.resultImages.push('')
        }
    }
    if (reqsItem.value.progress == 100) {
        fabType.value = 'user'
    }

}

// 记录index
const intervalChange = (e) => {
    index.value = e.detail.current
}

//下载图片
const download = async () => {
    loadingText.value = '图片获取中...'
    loadingStore.setLoading(true)
    
    downloadImg(reqsItem.value.downLoadList[index.value])

}

// 预览图片
const previewImage = () => {
    previewModel(reqsItem.value.resultImages, index.value)
}

// 发起生图任务
const getImg2Img = async () => {

    loadingText.value = '任务提交中...'
    loadingStore.setLoading(true)

    formdata.value.picBatch = picBatch.value[batch_index.value].value

    uni.uploadFile({
        url: BASE_URL + '/img2img', //仅为示例，非真实的接口地址
        filePath: filedata.value,
        name: 'filedata',
        header: {
            Authorization: 'bearer ' + token.value,
        },
        formData: {
            'filedata': filedata.value,
            'filedata1': filedata1.value,
            'filedata2': filedata2.value,
            'paramStr': JSON.stringify(formdata.value),
            'cost': cost.value
        },
        success(res) {

            const data = JSON.parse(res.data)

            if (res.statusCode === 401) {
                uni.showToast({
                    title: "请登录后进行操作",
                    icon: "none",
                    success: () => {
                        setTimeout(() => {
                            uni.navigateTo({
                                url: '/pages/login/login'
                            })
                        }, 500)
                    }
                })
                return
            }
            if (res.statusCode === 500) {
                uni.showToast({
                    title: data.msg,
                    icon: "none",
                    showCancel: false,
                    confirmColor: '#000',
                    duration: 3000
                })
                setTimeout(() => {
                    loadingStore.setLoading(false)
                }, 3000)
                return
            }

            loadingStore.setLoading(false)

            let form = {
                'filedata': filedata.value,
                'filedata1': filedata1.value,
                'filedata2': filedata2.value,
                'paramStr': JSON.stringify(formdata.value),
                'cost': cost.value
            }

            if (data.code === 0) {
                uni.redirectTo({
                    url: '/pages/drawInfo/drawInfo?id=' + data.data + '&formData=' + JSON
                        .stringify(form)
                })
            }
        },
        fail: function (err) {
            uni.showModal({
                content: "线稿图已丢失，请点击返回按钮并重新上传线稿图",
                icon: "none",
                confirmText: '返回',
                success: function (res) {
                    if (res.confirm) {
                        uni.reLaunch({
                            url: '/pages/draw/draw'
                        });
                    }
                }
            })
        },
        complete: function () {
            loadingStore.setLoading(false)
        }
    })
}

// 监听页面隐藏
onHide(() => {
    loadingStore.setLoading(false)
})
</script>

<style lang="scss" scoped>
.ing {
    margin: 284rpx auto 0;
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;

    .title {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        height: 22rpx;
        line-height: 22rpx;
        font-size: 22rpx;
        color: #e6e6e6;
        font-weight: 400;
        margin-bottom: 20rpx;
    }

    .progress-container {
        width: 480rpx;
        height: 32rpx;
        background: linear-gradient(0deg, #ff8a63 0%, #ffde7d 100%);
        border-radius: 5rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        .content {
            height: 28rpx;
            width: calc(100% - 4rpx);
            background: #000;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 0 12rpx;

            &:deep(.uv-line-progress) {

                // .uv-line-progress__background{
                //     background: linear-gradient(0deg,#ff8a63 0%, #ffde7d 100%) !important;
                // }
                .uv-line-progress__line {
                    background: linear-gradient(0deg, #ff8a63 0%, #ffde7d 100%) !important;
                }
            }
        }
    }

    .tip-container{
        margin-top: 200rpx;
        .tip{
            color: #fff;
            font-size: 24rpx;
            line-height: 40rpx;
            width: 100%;
            display: flex;
            justify-content: center;
        }
    }
}


.content {
    width: 686rpx;
    margin: 0 auto;

    .swiper {
        width: 100%;
        height: 514rpx;
        border-radius: 20rpx;
        overflow: hidden;
        background: #191919;

        .swiper-item {
            height: 100%;

            .swiper-item-img {
                width: 100%;
                height: 100%;
            }

            .block {
                width: 100%;
                height: 100%;
                background: #191919;
                display: flex;
                flex-direction: column;
                align-items: center;

                .block-icon {
                    margin-top: 140rpx;
                }

                .text {
                    margin-top: 40rpx;
                    color: #fff;
                    font-size: 24rpx;
                    width: 100%;
                    text-align: center;
                }
            }
        }
    }

    .dots {
        width: 100%;
        height: 66rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        .dots-item {
            width: 8rpx;
            height: 8rpx;
            background-color: #999;
            margin: 0 4rpx;
            border-radius: 4rpx;

            &.actived {
                width: 24rpx;
                background-color: #fff;
            }
        }
    }
}

.btn-conainer {
    width: 100%;
    height: 72rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #000;
    font-size: 24rpx;
    font-weight: 700;

    .high {
        width: 480rpx;
        height: 72rpx;
        background: #ffcb30;
        border-radius: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .down {
        width: 176rpx;
        height: 72rpx;
        background: #e6e6e6;
        border-radius: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}

.controller {
    height: 186rpx;
    width: 100%;
    background: #000;
    position: fixed;
    bottom: var(--window-bottom);
    left: 0;
    padding: 0 32rpx;
    box-sizing: border-box;

    .batch {
        height: 40rpx;
        margin: 24rpx auto;
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .text {
            font-size: 24rpx;
            font-weight: 500;
            color: #ffffff;
        }

        .batch-container {
            display: flex;

            .item {
                width: 112rpx;
                height: 40rpx;
                line-height: 40rpx;
                background: #333333;
                border-radius: 20rpx;
                font-size: 24rpx;
                font-weight: 500;
                text-align: center;
                color: #999999;
                margin-left: 16rpx;

                &.actived {
                    background: #ffffff;
                    color: #000;
                }
            }
        }
    }

    .btn {
        width: 100%;
        height: 78rpx;
        border-radius: 39rpx;
        color: #080808;
        align-items: flex-end;

        .btn-text {
            font-size: 30rpx;
            font-weight: 700;
            line-height: 78rpx;
        }

        .btn-price {
            font-weight: 500;
            font-size: 18rpx;
            line-height: 60rpx;
            letter-spacing: 2.8rpx;
        }
    }
}
</style>